package org.jeecg.modules.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.c.entity.MSC;
import org.jeecg.modules.c.service.IMSCService;
import org.jeecg.modules.client.NettyClient;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;


@Component
@Slf4j
public class HeadJob implements Job {

    private static final int head = 20;
    private static final int headAck = 60;
    private static final int headRetry = 10;


    @Autowired
    private IMSCService mSCService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //获取正常连接的sc

        List<MSC> list = mSCService.list();
        //在字典中获取心跳间隔配置。先按照缺省设置 todo
        //遍历sc
        for (MSC msc : list) {
            //判断上次发送时间和当前时间对比是否大于10秒，大于就发送心跳包，否则不发
            Date headDate = msc.getHead();
            Date headAckDate = msc.getHeadAck();

            if(headDate==null){
                //直接发送心跳包

            }else {
                //计算时间秒差
                long time = new Date().getSeconds()-headDate.getSeconds();
                if(time>head){
                    //发送心跳包
                    log.info("发送心跳包");

                }
                //链接监测
                if(headAckDate!=null){
                    long acktime =   new Date().getSeconds()-headAckDate.getSeconds();
                    if(acktime>headAck){
                        //断开连接
                        log.info("断开连接");
                        mSCService.update(null,new UpdateWrapper<MSC>().eq("scid",msc.getScid()).set("scstatus",0));
                    }
                    //如果确认链接超过70 秒，则重新连接
                    if(acktime>headAck+headRetry){
                        //重新连接
                        log.info("重新连接");
                        NettyClient.start(msc);
                    }
                }

            }



        }

        //心跳监测任务

    }
}
